<?php

namespace app\controller;

use app\BaseController;
use app\model\SysMenu;
use app\model\User as UserModel;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\helper\Str;
use think\captcha\facade\Captcha;
use app\controller\CommonPayController;

class UsersController extends BaseController
{
    public function login(Request $request)
    {
        $userLoginState = Cache::get('userLoginState');
        $userName = $request::param('username');
        $password = $request::param('password');
        $mo = new UserModel();
        if ($mo->dellogin($userName, $password) != false) {
            return $this->returnJson(1002, '账号被禁用！');
        }
        $ret = $mo->login($userName, $password);
        if ($ret != false) {
            $rand = Str::random(32);
            Cache::set('userLoginInfo_' . $rand, $ret, 7200);
            if (empty($userLoginState[$userName])) {
                $userLoginState[$userName] = $rand;
                Cache::set('userLoginState', $userLoginState);
            } else {
                Cache::delete('userLoginInfo_' . $userLoginState[$userName]);
                $userLoginState[$userName] = $rand;
                Cache::set('userLoginState', $userLoginState);
            }
            return $this->returnJson(1001, '登录成功', ['key' => $rand]);
        } else {
            return $this->returnJson(1002, '用户名密码错误');
        }
    }

    public function checkAccount(Request $request)
    {
        $userName = $request::param('username');
        $mo = new UserModel();
        $ret = $mo->checkAccount($userName);
        if ($ret !== false) {
            return $this->returnJson(1002, '账号已经存在', $ret);
        } else {
            return $this->returnJson(1001, '可以注册', $ret);
        }
    }

    /**
     * 用户自己注册
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saveData()
    {
        $mo = new UserModel();
        $msgCode = $this->request->post('msgCode');
        $param = $this->request->only(['login_name', 'company_name', 'industry', 'address', 'main_product', 'password', 'mobile']);
        $code = Cache::get('register.' . $param['mobile']);
        if (empty($msgCode) || $code != $msgCode) {
            return $this->returnJson(1002, '短信验证码错误');
        }
        $this->validate($param, 'user.register');
        $defaultComboInfo = Db::table('lyx_combo')->find(1);
        $param['password'] = md5($param['password']);
        $param['pay_time'] = time();
        $param['how_long_time'] = $defaultComboInfo['how_long_time'];
        $param['create_time'] = toDate(time());
        $param['update_time'] = toDate(time());

        $ret = $mo->editData($param);
        if ($ret != false) {
            return $this->returnJson(1001, '注册成功');
        } else {
            return $this->returnJson(1002, '注册失败');
        }
    }

    public function changePwd()
    {
        $mo = new UserModel();
        $msgCode = $this->request->post('msgCode');
        $param = $this->request->only(['login_name', 'password', 'mobile']);
        $code = Cache::get('register.' . $param['mobile']);
        if (empty($msgCode) || $code != $msgCode) {
            return $this->returnJson(1002, '短信验证码错误');
        }

        $info = Db::name('user')->where('login_name', $param['mobile'])->find();
        if ($info != false) {
            $info['password'] = md5($param['password']);
        }

        $ret = $mo->editData($info);
        if ($ret != false) {
            return $this->returnJson(1001, '修改成功');
        } else {
            return $this->returnJson(1002, '修改失败');
        }
    }

    /**
     * 注册的时候发送短信验证码
     *
     * @param Request $request
     *
     * @return \think\Response
     */
    public function sendMsg(Request $request)
    {
        $param = $request::param();
        $captcha = new Captcha();
        if ($captcha::check($param['code'])) {
            $code = rand(11111, 999999);
            Cache::set('register.' . $param['mobile'], $code);
            $msg = new \app\controller\SendMsgController();
            $ret = $msg->sendCode($param['mobile'], $code);
            if ($ret) {
                return $this->returnJson(1001, '发送成功');
            } else {
                return $this->returnJson(1002, '发送失败');
            }
        } else {
            return $this->returnJson(1020, '图片验证码错误');
        }

    }

    /**
     * 验证码图片
     * @return \think\Response
     */
    public function verify()
    {
        return Captcha::create();
    }

    public function userCreateOrder(Request $request)
    {
        $param = $request::param();
        $userInfo = getLoginInfo();
        if (empty($param['combo_id']) || empty($param['pay_type']) || empty($param['num'])) {
            return $this->returnJson(1002, '缺少参数');
        }

        $info = Db::name('combo')->find($param['combo_id']);
        if ($info != false) {
            $data['order_no'] = 'NO' . rand(111111111, 999999999);
            $data['title'] = $info['title'];
            $data['user_id'] = $userInfo['id'];
            $data['money'] = $info['price'];
            $data['type'] = 1;
            $data['num'] = $param['num'];
            $data['search_pay_type'] = $param['searchPayType'];
            $data['combo_id'] = $info['id'];
            $data['create_time'] = toDate(time());


            $list = Db::name('order')->where('user_id', $userInfo['id'])->where('type', 2)->select()->toArray();
            $type = 2; //--2是一个账号，3-是6个账号
            $money_price = $info['price'];
            $count = 0;
            if ($list != false) {
                foreach ($list as $value) {
                    if ($value['combo_id'] == 2) {//--2代表套餐是单账号的 这个不能变
                        $count += $value['num'];
                    } else {
                        $type = 3;
                    }
                }
            } else {
                $type = 1;// 没购买过
            }


            if ($param['searchPayType'] != 0 && $type != 1) {
                if ($param['searchPayType'] == 1) {//为本账号续费
                    if (($type == 2 && $info['next_num'] <= $count) || $type == 3) {
                        $money_price = $info['next_price'];
                    }
                    $data['money'] = $money_price;
                    $data['num'] = 1;
                }
                if ($param['searchPayType'] == 2) {//添加新账号
                    if (($type == 2 && $info['next_num'] <= $count) || $type == 3) {
                        $money_price = $info['next_price'];
                    }
                    $data['money'] = $money_price * $data['num'];
                }
                if ($param['searchPayType'] == 3) {//在该账号下添加6个账号
                    $data['money'] = $money_price;
                    $data['num'] = 1;
                }
                if ($param['searchPayType'] == 4) {//在该账号下添加5个账号为自己续费一年
                    $data['money'] = $money_price;
                    $data['num'] = 1;
                }
            }

            $ret = Db::name('order')->save($data);
            if ($ret != false) {
                $pay = new CommonPayController();
                if ($param['pay_type'] == 2) {
                    $url = $pay->getPayCord($data['order_no'], $data['title'], $data['money']);
                    $upData['pay_type'] = 2;
                } else {
                    $url = $pay->getAliPayUrl($data['order_no'], $data['title'], $data['money']);
                    $upData['pay_type'] = 1;
                }
                $upData['pay_url'] = $url;
                Db::name('order')->where('order_no', $data['order_no'])->update($upData);
                return $this->returnJson(1001, '获取支付二维码', ['order' => $data['order_no'], 'pay_url' => $url]);
            } else {
                return $this->returnJson(1002, '下单失败');
            }
        } else {
            return $this->returnJson(1002, '没有这个套餐');
        }
    }

    /**
     * 判断是否支付成功
     *
     * @param Request $request
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkOrderStatus(Request $request)
    {
        $param = $request::param();
        $ret = Db::name('order')->where('order_no', $param['order'])->field('transaction_id,type,pay_time')->find();
        if ($ret['type'] == 2) {
            updateLoginInfo();
            return $this->returnJson(1001, '支付成功');
        }

        return $this->returnJson(1002, '没支付');
    }

    /**
     * 用户更改密码
     *
     * @param Request $request
     *
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function userChangePwd(Request $request)
    {
        $pwd = $request::param('pwd');
        $changeId = $request::param('changeId');
        if (empty($changeId)) {
            $userInfo = getLoginInfo();
        } else {
            $userInfo['id'] = $changeId;
        }
        $ret = Db::name('user')->where('id', $userInfo['id'])->update(['password' => md5($pwd)]);
        if ($ret != false) {
            return $this->returnJson(1001, '修改成功');
        } else {
            return $this->returnJson(1002, '密码修改失败');
        }
    }

    public function getUserBuyList()
    {
        $userInfo = getLoginInfo();
        $list = Db::name('order')->where('user_id', $userInfo['id'])->where('type', 2)->select()->toArray();
        $type = 2; //--2是一个账号，3-是6个账号
        $count = 0;
        if ($list != false) {
            foreach ($list as $value) {
                if ($value['combo_id'] == 2) {//--2代表套餐是单账号的 这个不能变
                    $count += $value['num'];
                } else {
                    $type = 3;
                }
            }
            return $this->returnJson(1001, '购买过', ['count' => $count, 'type' => $type]);
        } else {
            return $this->returnJson(1002, '没有购买过');
        }
    }

    /**
     * 定时任务执行订单 更新
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function runOrderUsed()
    {
        $orderId = Db::name('order')->where('type', 2)->where('is_used', 1)->field('id,order_no')->find();
        $orderLogic = new \app\logic\OrderLogic();
        $orderLogic->userOrderAddTime($orderId['order_no']);
    }

    public function getCountChild()
    {
        $userInfo = getLoginInfo();
        $count = Db::name('user')->where('pid', $userInfo['id'])->count();
        $maxNum = Db::name('user')->where('id', $userInfo['id'])->field('max_num')->find();
        if ($count > 0) {
            return $this->returnJson(1001, '总共数量', ['child_count'=>$count,'max_num'=>$maxNum['max_num']]);
        } else {
            return $this->returnJson(1001, '总共数量', 0);

        }
    }

    public function getComboList()
    {
        $list = Db::name('combo')->where('id', '>', 1)->select()->toArray();
        if ($list != false) {
            return $this->returnJson(1001, '获取数据成功', $list);
        } else {
            return $this->returnJson(1002, '没有套餐');

        }
    }

    public function uploadFiles(Request $request){
        // 上传文件错误或者文件验证不通过时，都会抛出异常，所以要使用try来捕捉异常
        try {
            $file = $request::file('file');
            // 如果上传的文件为null，手动抛出一个异常，统一处理异常
            if (null === $file) {
                // 异常代码使用UPLOAD_ERR_NO_FILE常量，方便需要进一步处理异常时使用
                throw new \Exception('请上传文件', UPLOAD_ERR_NO_FILE);
            }

            // 使用验证器验证上传的文件
            validate(['file' => [
                // 限制文件大小(单位b)，这里限制为4M
                'fileSize' => 4 * 1024 * 1024,
                // 限制文件后缀，多个后缀以英文逗号分割
                'fileExt'  => 'gif,jpg,png,mp4'
                // 更多规则请看“上传验证”的规则，文档地址https://www.kancloud.cn/manual/thinkphp6_0/1037629#_444
            ]])->check(['file' => $file]);

            // 保存路径，实际保存路径为“磁盘路径” + “avatar”
            $path = 'avatar';
            // 文件名规则，默认是当前时间。可以使用哈希算法，如：md5,sha1等。还可以传入匿名函数
            $rule = 'md5';
            // 将文件保存public磁盘，文件名为$rule指定的规则。然后将文件路径赋值给$path
            $path = \think\facade\Filesystem::disk('public')->putFile($path, $file, $rule);
            // 拼接URL路径
            $url = \think\facade\Filesystem::getDiskConfig('public', 'url') . '/' . str_replace('\\', '/', $path);
        } catch (\Exception $e) {
            // 如果上传时有异常，会执行这里的代码，可以在这里处理异常
            return json([
                'errcode' => 1,
                'errmsg'  => $e->getMessage(),
            ]);
        }

        $info = [
            // 文件路径：public/storage/avatar/20160510/42a79759f284b767dfcb2a0197904287.jpg
            'path' => $path,
            // URL路径：public/storage/avatar/20160510/42a79759f284b767dfcb2a0197904287.jpg
            'url'  => $url,
            // 文件大小（字节）
            'size' => $file->getSize(),
            // 文件名：读书顶个鸟用.jpg
            'name' => $file->getFilename(),
            // 文件MINE：image/jpeg
            'mine' => $file->getMime(),
        ];
        return $this->returnJson(1001, '上传成功',$info);
    }

}
